"""

@Date    ：2025-08-16 8:55 
"""
from datetime import datetime

from django.utils.deprecation import MiddlewareMixin
from django.core.handlers.wsgi import WSGIRequest
from django.http.response import HttpResponse


class CountRequestTime(MiddlewareMixin):
    def __init__(self, get_response):
        super().__init__(get_response)
        self.start_time = None
        self.end_time = None

    def process_request(self, request: WSGIRequest):
        # 计算时间
        self.start_time = datetime.now()
        return

    def process_exception(self, request: WSGIRequest, exception: Exception):
        self.end_time = datetime.now()
        print(f'本次请求异常，共花费{int((self.end_time - self.start_time).total_seconds() * 1000)}毫秒')
        return

    def process_response(self, request: WSGIRequest, response: HttpResponse):
        self.end_time = datetime.now()
        print(f'本次请求成功，花费{int((self.end_time - self.start_time).total_seconds() * 1000)}毫秒')
        return response
